<template>
  <div class="addBulletinBoardDialog__container">
    <el-dialog
      v-model="dialogVisible"
      draggable
      :title="isEdit ? '编辑字段' : '新增字段'"
      width="70%"
      :before-close="beforeClose"
    >
      <div class="addBulletinBoardDialog__body__container">
        <el-form
          ref="ruleFormRef"
          status-icon
          :model="form"
          label-width="120px"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="看板显示内容" prop="label">
                <el-input
                  v-model="form.label"
                  type="text"
                  clearable
                  placeholder="看板显示内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="看板中是否显示" prop="isListShow">
                <el-radio-group v-model="form.isListShow">
                  <el-radio :label="0">不显示</el-radio>
                  <el-radio :label="1">显示</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表单中是否显示" prop="isFormShow">
                <el-radio-group v-model="form.isFormShow">
                  <el-radio :label="0">不显示</el-radio>
                  <el-radio :label="1">显示</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="app中是否显示" prop="isAppShow">
                <el-radio-group v-model="form.isAppShow">
                  <el-radio :label="0">不显示</el-radio>
                  <el-radio :label="1">显示</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否必填" prop="required">
                <el-radio-group v-model="form.required">
                  <el-radio :label="false">非必填</el-radio>
                  <el-radio :label="true">必填</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.required">
              <el-form-item label="错误提示内容" prop="message">
                <el-input
                  v-model="form.message"
                  type="text"
                  clearable
                  placeholder="输入错误提示内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" class="form_item">
              <el-form-item label="能否删除" prop="canDel">
                <el-radio-group
                  v-model="form.canDel"
                  :disabled="noDelKeyList.indexOf(form.key) !== -1"
                >
                  <el-radio :label="0">不能删除</el-radio>
                  <el-radio :label="1">能删除</el-radio>
                </el-radio-group>
                <div
                  class="form_tips-error"
                  v-if="noDelKeyList.indexOf(form.key) !== -1"
                >
                  *** 该字段无法变更
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="字段类型" prop="formType">
                <el-select v-model="form.formType" placeholder="请选择字段类型">
                  <el-option
                    v-for="item in formTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="24"
              v-if="form.formType == 'radio' || form.formType == 'checkbox'"
            >
              <div class="option-container">
                <div class="option_title">*添加选项</div>
                <div class="option_list-container">
                  <template v-if="form.option.length">
                    <div
                      class="list_item-container"
                      v-for="(optItem, optIndex) in form.option"
                      :key="optIndex"
                    >
                      <span
                        >{{ String.fromCharCode(optIndex + 1 + 64) }}、</span
                      >
                      <div class="item_formItem-container">
                        <span class="formItem_label">选项说明：</span>
                        <el-input
                          v-model="optItem.label"
                          type="text"
                        ></el-input>
                      </div>
                      <div class="item_formItem-container">
                        <span class="formItem_label">选项值：</span>
                        <el-input
                          v-model="optItem.value"
                          type="text"
                        ></el-input>
                      </div>
                      <el-button
                        type="danger"
                        @click.stop="delOptionFun(form.option, optIndex)"
                        >删除</el-button
                      >
                    </div>
                  </template>

                  <el-button type="primary" @click.stop="addOption(form.option)"
                    >添加</el-button
                  >
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="onSubmit(ruleFormRef as FormInstance)"
            >确定</el-button
          >
          <el-button @click="beforeClose(null)" type="default">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="AddBulletinBoardDialog">
import { editOrderField, addOrderField } from "@/api/order/index";

const dialogVisible = ref(false);
const isEdit = ref<boolean>(false);
const handleOpen = (data: any) => {
  console.log("当前对象  ", data);
  isEdit.value = data.isEdit;

  if (isEdit.value) {
    // loading.value = false
    let row = data.row;
    let required = false;
    let message = "";
    if (
      row.rule &&
      (row.rule[0].required === true || row.rule[0].required === "true")
    ) {
      required = true;
    }
    if (row.rule && row.rule[0].message) {
      message = row.rule[0].message;
    }
    console.log("row----- ", row);
    console.log("row.option  ", row.option);
    let target = {
      ...row,
      required,
      message,
    };
    console.log("target --------  ", target);
    form.value = Object.assign(form.value, target);
    console.log("赋值后的form  ", form.value);
  } else {
    form.value = {
      // 下面是依据后端字段编写
      formType: "input",
      isListShow: 1, // 是否在看板中显示
      isFormShow: 1, // 是否在表单中显示
      isAppShow: 0, // 是否在app中显示
      key: "",
      label: "", // 看板显示内容
      option: [],
      value: "", // 添加工单是的表单值
      rule: [],
      canDel: 0, // 能否删除

      required: true,
      message: "",
      fieldId: 0,
    };
  }
  console.log("赋值后的form.option  ", form.value.option);
  dialogVisible.value = true;
};

// 表单处理
import type { FormInstance, FormRules } from "element-plus";
const emits = defineEmits(["submitSuccess"]);
const ruleFormRef = ref<FormInstance>();
// 表单对象接口
interface RuleForm {
  formType: string;
  isListShow: number; // 是否在看板中显示
  isFormShow: number; // 是否在表单中显示
  isAppShow: number; // app中是否显示
  key: string;
  label: string; // 看板显示内容
  option: any[];
  value: string; // 添加工单是的表单值
  rule: any[];
  canDel: number; // 能否删除
  required?: true;
  message?: string;
  fieldId: number;
}
// 选项单个接口
interface OptionItem {
  label: string;
  value: number | string;
}

let form = ref<RuleForm>({
  // 下面是依据后端字段编写
  formType: "input",
  isListShow: 1, // 是否在看板中显示
  isFormShow: 1, // 是否在表单中显示
  isAppShow: 0, // app中是否显示
  key: "",
  label: "", // 看板显示内容
  option: [],
  value: "", // 添加工单是的表单值
  rule: [],
  canDel: 0, // 能否删除
  required: true,
  message: "",
  fieldId: 0,
});
const rules = reactive<FormRules<RuleForm>>({
  label: [{ required: true, message: "请输入看板显示内容", trigger: "blur" }],
  formType: [{ required: true, message: "请选择字段类型", trigger: "blur" }],
  isListShow: [{ required: true, message: "请选择是否显示", trigger: "blur" }],
  isFormShow: [{ required: true, message: "请选择是否显示", trigger: "blur" }],
  required: [{ required: true, message: "请选择是否必填", trigger: "blur" }],
  message: [{ required: true, message: "请输入错误提示内容", trigger: "blur" }],
  canDel: [{ required: true, message: "请选择能否删除", trigger: "blur" }],
});
const formTypeList = [
  {
    label: "输入框",
    value: "input",
  },
  {
    label: "单选",
    value: "radio",
  },
  {
    label: "多选",
    value: "checkbox",
  },
  {
    label: "数字输入",
    value: "number",
  },
  {
    label: "文本说明",
    value: "textarea",
  },
  {
    label: "日期时间选择",
    value: "datetime",
  },
  {
    label: "只读",
    value: "read",
  },
  {
    label: "图片",
    value: "image",
  },
  {
    value: "craftState",
    label: "工艺内容",
  },
  {
    value: "amount",
    label: "金额输入",
  },
];

const noDelKeyList = [
  "password",
  "error_number",
  "not_received_money",
  "received_money",
  "order_money",
  "day",
  "craft_state",
  "product_images",
  "craft_images",
  "remark",
  "urgency",
  "order_state",
  "customer_name",
  "sell_goods_time",
  "stock_goods_time",
  "style",
  "number",
];

const delOptionFun = (list: OptionItem[], index: number) => {
  if (!list || !list.length) return;
  list.splice(index, 1);
};

const addOption = (list: OptionItem[]) => {
  list.push({
    label: "选项",
    value: "说明",
  });
};

const onSubmit = async (ruleFormRef: FormInstance) => {
  console.log("ruleForm  ", ruleFormRef);
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid, fields) => {
    if (valid) {
      console.log("submit! 表单结果 ", form);
      // return
      if (isEdit.value) {
        ElMessageBox.confirm("您确定要修改该字段吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            confirmDialog();
          })
          .catch(() => {
            ElMessage({
              message: "已取消",
              type: "info",
            });
          });
      } else {
        ElMessageBox.confirm("您确定要添加该字段吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            confirmDialog();
          })
          .catch(() => {
            ElMessage({
              message: "已取消",
              type: "info",
            });
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const confirmDialog = async () => {
  console.log("form --- ", form.value);
  let ruleNew = [
    {
      required: form.value.required,
      message: form.value.message,
      trigger: "blur",
    },
  ];
  let params = {
    ...form.value,
    rule: ruleNew,
  };
  delete params.required;
  delete params.message;
  console.log("params ------  ", params);
  let res = isEdit.value
    ? await editOrderField(params.fieldId, params)
    : await addOrderField(params);
  if (res) {
    if (!isEdit.value) {
      // 新增
      ElMessage({
        message: "添加成功",
        type: "success",
      });
    } else {
      // 编辑
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
    beforeClose(null);
    emits("submitSuccess");
  }
};

const onReset = () => {
  // 重置表单
  console.log("清空了  ", ruleFormRef);
  if (!ruleFormRef || !ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};

const beforeClose = (done: Function | null) => {
  onReset();
  isEdit.value = false;
  if (typeof done === "function") {
    done();
  } else {
    dialogVisible.value = false;
  }
};

defineExpose({
  handleOpen,
});
</script>

<style lang="scss" scoped>
.addBulletinBoardDialog__container {
  .addBulletinBoardDialog__body__container {
    box-sizing: border-box;
    padding-right: 15px;
    max-height: 70vh;
    overflow-y: auto;
    .form_tips-error {
      font-size: 12px;
      color: red;
      line-height: 10px;
    }
    .option-container {
      .option_title {
        width: 120px;
        text-align: right;
        font-weight: bold;
        margin-bottom: 16px;
      }
      .option_list-container {
        padding-left: 100px;
        .list_item-container {
          display: flex;
          align-items: center;
          margin-bottom: 15px;
          .item_formItem-container {
            flex: 1 1 auto;
            margin-right: 15px;
            display: flex;
            align-items: center;
            .formItem_label {
              flex-shrink: 0;
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.addBulletinBoardDialog__container {
  .addBulletinBoardDialog__body__container {
    .form_item {
      .ep-form-item__content {
        display: block;
      }
    }
  }
}
</style>
